package dbtools;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class WeiboDb {
	
	public static final Log log = LogFactory.getLog(WeiboDb.class);
	
	private Connection connect = null;
	Statement stmt = null;
	
	private final int pageSize = 200;

	public WeiboDb() {
		this.reginster();
		this.conDB();
		try {
			stmt = this.connect.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	private void reginster() {
		try {
			Class.forName("com.mysql.jdbc.Driver"); // ����MYSQL JDBC�����
			// System.out.println("Success loading Mysql Driver!");
		} catch (Exception e) {
			System.out.print("Error loading Mysql Driver!");
			e.printStackTrace();
		}
	}

	private Connection conDB() {
		Connection connect = null;
		try {
			connect = DriverManager
					.getConnection(
							"jdbc:mysql://localhost/weibo?useUnicode=true&characterEncoding=utf-8",
							"root", "root");
			System.out.println("Success connect Mysql server!");
		} catch (Exception e) {
			System.out.print("get data error!");
			e.printStackTrace();
		}
		this.connect = connect;
		return connect;
	}

	public void update(String sql){
		try {
			stmt.clearBatch();
			stmt.execute("set names utf8"); // lpg 2012.2.21
			stmt.execute(sql);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			log.debug(e1);
			log.debug(sql);
		} finally {
			
		}
	}
	
	public final void dispose(){
		try{
			if (stmt != null)
				stmt.close();
			if (connect != null)
				connect.close();
		}catch(Exception e){
			log.debug(e);
		}finally{
			
		}
	}
	
	public final List<String> getWeiboId(int start){
		List<String> ret = new ArrayList<String>();
		
		StringBuilder sb = new StringBuilder("select id from baseinfo limit ");
		sb.append(String.valueOf(start));
		sb.append(",").append(String.valueOf(pageSize));
		
		try {
			ResultSet rs = stmt.executeQuery(sb.toString());
			if (rs != null){
				while(rs.next()){
					ret.add(rs.getString("id"));
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.debug(e);
			log.debug(sb.toString());
		}
		
		return ret;
	}

}
